<template>
  <div>
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: '/settlement-management/settlement-maintenance-approval'
          }"
          >结算管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: '/settlement-management/settlement-maintenance-approval'
          }"
          >物资结算管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path:
              '/settlement-management/settlement-written-off/settlement-unsubmitted'
          }"
          >结算单冲销</el-breadcrumb-item
        >
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb">{{ editOrCreate }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          class="el-tabs__customize"
        >
          <el-tab-pane label="基本信息" name="first">
            <addInformation
              ref="baseInfo"
              :settlementList="settlementList"
            ></addInformation>
          </el-tab-pane>

          <el-tab-pane label="结算单明细" name="second">
            <financeInfoCheck
              ref="settlementDetail2"
              :settlementList="settlementList"
            ></financeInfoCheck>
          </el-tab-pane>

          <el-tab-pane label="验收单明细" name="third">
            <purchaseListCheck
              ref="acceptanceDetail"
              :acceptanceList="settlementList"
            ></purchaseListCheck>
          </el-tab-pane>
          <el-tab-pane
            label="附件"
            name="fourth"
            v-if="isTrue"
            class="file-group"
          >
            <fileInfo ref="fileInfo" v-model="fileList"></fileInfo>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button type="bottom" icon="icon-ccui-save" @click="saveHandle"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save-submit"
            @click="submitHandle"
            >保存并提交</el-button
          >
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import { getSessionItem, ishasAgentId } from "@/basa/utils";
import addInformation from "../addPages/add-information";
import fileInfo from "@/basa/components/public/uploadInfo2";
import {
  getSettlementWriteById,
  saveSettlementWrite,
  editSettlementWrite
} from "../../api/settlement-written-off.js";
import financeInfoCheck from "../components/financeInfoEditCheck";
import purchaseListCheck from "../components/purchaseListCheck";

export default {
  name: "listquery-new-item",
  props: {
    state: {
      type: String,
      default: ""
    }
  },
  components: {
    addInformation,
    fileInfo,
    purchaseListCheck,
    financeInfoCheck,
  },
  data() {
    return {
      settlementList: [],
      acceptanceList:[],//验收单清单
      activeName: "first",
      title: "新增信息",
      submitFlag: false,
      taxRateList: [],
      id: "",
      fileList: [],
      editOrCreate: "",
      isTrue: false
    };
  },
  watch: {
    $route(to, form) {
      if (to.name == "contracts-contractMeasurement-add-item") {
        this.activeName = "first";
      }
    }
  },
  created() {
    this.id = this.$route.params.id;
    // let idArr = [];
    // idArr.push(this.id);
    if (this.state === "create") {
      this.isTrue = true;
      this.editOrCreate = "新增结算冲销单";
      this.$store.state.isEdit = false;
    } else if (this.state === "edit") {
      this.$store.state.isEdit = true;
      //调用查看详情结算单接口
      const obj = {
        id: this.id
      };
     
      getSettlementWriteById(obj).then(res => {
        res.data.data.settlementWriteOffBO.reversal = [
          res.data.data.settlementWriteOffBO.writeoffStart,
          res.data.data.settlementWriteOffBO.writeoffEnd
        ];
        this.$refs.baseInfo.form = res.data.data.settlementWriteOffBO;
        this.editOrCreate = "编辑 " + res.data.data.settlementWriteOffBO.writeoffName;
        this.$refs.baseInfo.form.contractMoney =
          res.data.data.settlementWriteOffBO.contractMoney !== null &&
          res.data.data.settlementWriteOffBO.contractMoney !== undefined
            ? (+res.data.data.settlementWriteOffBO.contractMoney).toFixed(2)
            : "";
        this.$refs.baseInfo.form.writeoffMoney =
          res.data.data.settlementWriteOffBO.writeoffMoney !== null &&
          res.data.data.settlementWriteOffBO.writeoffMoney !== undefined
            ? (+res.data.data.settlementWriteOffBO.writeoffMoney).toFixed(2)
            : "";
        this.$refs.baseInfo.form.writeoffCount =
          res.data.data.settlementWriteOffBO.writeoffCount !== null &&
          res.data.data.settlementWriteOffBO.writeoffCount !== undefined
            ? (+res.data.data.settlementWriteOffBO.writeoffCount).toFixed(3)
            : "";
        this.$refs.fileInfo = res.data.data.writeOffFiles;
        this.isTrue = true;
        this.fileList = res.data.data.writeOffFiles;
        this.fileList.forEach(item => {
          item.createTime = item.uploadTime;
          item.uploadId = item.fileInfoId;
          item.fileSize = Math.floor(item.fileSize / 1024) + "kb"
        });
        this.settlementList = res.data.data.settlementBOList;
        this.settlementList.forEach(item => {
          // 结算单明细的表处理
          item.settlementCount =
            item.settlementCount !== null && item.settlementCount !== undefined
              ? (+item.settlementCount).toFixed(3)
              : "";
          item.settlementCountTotal =
            item.settlementCountTotal !== null &&
            item.settlementCountTotal !== undefined
              ? (+item.settlementCountTotal).toFixed(2)
              : "";

          item.unitPriceWithTax =
            item.unitPriceWithTax !== null &&
            item.unitPriceWithTax !== undefined
              ? (+item.unitPriceWithTax).toFixed(2)
              : "";

          item.moneyWithoutTax =
            item.moneyWithoutTax !== null && item.moneyWithoutTax !== undefined
              ? (+item.moneyWithoutTax).toFixed(2)
              : "";

          item.moneyWithTax =
            item.moneyWithTax !== null && item.moneyWithTax !== undefined
              ? (+item.moneyWithTax).toFixed(2)
              : "";

          item.settlementMoneyTotal =
            item.settlementMoneyTotal !== null &&
            item.settlementMoneyTotal !== undefined
              ? (+item.settlementMoneyTotal).toFixed(2)
              : "";
          // 验收单明细表的数据处理
          item.orderCount =
            item.orderCount !== null && item.orderCount !== undefined
              ? (+item.orderCount).toFixed(3)
              : "";

          item.unTransportCount =
            item.unTransportCount !== null && item.unTransportCount !== undefined
              ? (+item.unTransportCount).toFixed(3)
              : "";

          item.settlementPrice =
            item.settlementPrice !== null && item.settlementPrice !== undefined
              ? (+item.settlementPrice).toFixed(2)
              : "";
        });
      });
    }
  },

  methods: {
    handleClick(tab, event) {
      this.activeName = tab.name;
    },
    async saveHandle() {
      try {
        let baseObj = await this.$refs.baseInfo.handleSubmit();
        baseObj.writeoffStart = baseObj.reversal[0];
        baseObj.writeoffEnd = baseObj.reversal[1];
        let fileList = JSON.parse(JSON.stringify(this.fileList))
        fileList.forEach((row,index) => {
          row.fileInfoId = row.uploadId;
          row.uploadTime = new Date(row.createTime.replace(/-/g,"/")).getTime();;
          row.sn = index
        });
        const data = {
          settlementWriteOffBO : baseObj,
          uploadIds:fileList,
          operType:0
        }
        if(this.state === "create"){
          saveSettlementWrite(data).then(res => {
            if(res.data.code == 0){
              this.$message({
                message: res.data.message,
                type: "success",
                showClose: true,
                ccuiCustom: true,
                duration: 2000
              });
              this.$router.push(
                "/settlement-management/settlement-written-off/settlement-unsubmitted"
              );
            }
          });
        }else{
          editSettlementWrite(data).then(res => {
          if(res.data.code == 0){
            this.$message({
              message: res.data.message,
              type: "success",
              showClose: true,
              ccuiCustom: true,
              duration: 2000
            });
            this.$router.push(
              "/settlement-management/settlement-written-off/settlement-unsubmitted"
            );
          }
        });
        }
      } catch (error) {
        this.activeName = error;
        this.$message({
          message: "必填项未填写，请填写后保存",
          type: "error",
          showClose: true,
          ccuiCustom: true,
          duration: 2000
        });
      }
    },
    async submitHandle() {
      try {
        let baseObj = await this.$refs.baseInfo.handleSubmit();
        baseObj.writeoffStart = baseObj.reversal[0];
        baseObj.writeoffEnd = baseObj.reversal[1];
        let fileList = JSON.parse(JSON.stringify(this.fileList))
        fileList.forEach((row,index) => {
          row.fileInfoId = row.uploadId;

          row.uploadTime = new Date(row.createTime.replace(/-/g,"/")).getTime();
          row.sn = index
        });
        const data = {
          settlementWriteOffBO : baseObj,
          uploadIds:fileList,
          operType:1
        }
        if(this.state === "create"){
          saveSettlementWrite(data).then(res => {
            this.$message({
              message: res.data.message,
              type: "success",
              showClose: true,
              ccuiCustom: true,
              duration: 2000
            });
            this.$router.push(
              "/settlement-management/settlement-written-off/settlement-approval"
            );
          });
        }else{
          editSettlementWrite(data).then(res => {
            this.$message({
              message: res.data.message,
              type: "success",
              showClose: true,
              ccuiCustom: true,
              duration: 2000
            });
            this.$router.push(
              "/settlement-management/settlement-written-off/settlement-approval"
            );
          });
        }
      } catch (error) {
        this.activeName = error;
        this.$message({
          message: "必填项未填写，请填写后保存",
          type: "error",
          showClose: true,
          ccuiCustom: true,
          duration: 2000
        });
      }
    },
    // 返回
    handleBack() {
      this.$router.push(
        sessionStorage.getItem("fromPath") ||
          "/settlement-management/settlement-written-off/settlement-unsubmitted"
      );
    },
    deleteAppend(index) {
      console.log(index);
      this.tableData.splice(index, 1);
      sessionStorage.setItem("addAppendList", JSON.stringify(this.tableData));
    }
  },

  computed: {
    // 获取面包屑
    getBreadcrumb() {
      return getSessionItem("breadcrumb");
    }
  },

  // 更改列表缓存状态
  beforeRouteLeave(to, from, next) {
    if (this.submitFlag === true) {
      for (var key in this.$vnode.parent.parent.componentInstance.cache) {
        delete this.$vnode.parent.parent.componentInstance.cache[
          ishasAgentId(to.path, key)
        ];
      }
    }
    next();
  }
};
</script>
<style lang="scss" scoped>
.el-group-title {
  min-height: 200px;
}
.el-input /deep/ input.el-input__inner {
  width: 260px;
  height: 30px;
  border-radius: 4px;
  border: 1px solid #cccccc;
}
.el-form-item-box {
  float: left;
  width: 325px;
  margin-left: 116px;
  margin-right: 60px;
  // 440px
}
.ccui-form .ccui-form-shortInput {
  width: 260px;
}
.ccui-form .ccui-form-textArea,
.ccui-form .ccui-form-textArea .el-textarea {
  width: 760px;
  height: 100px;
}
.el-form-item-textarea {
  float: left;
  width: 825px;
  margin-left: 116px;
}

.upload-demo {
  text-align: right;
  margin-bottom: 20px;
}
// /deep/.el-col-12 {
//   //   width: 500px;
// }
//新增页tab切换样式
/deep/.el-tabs__nav {
  font-size: 14px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #333333;
}
/deep/.el-tabs__item {
  padding: 0 15px;
}

/deep/ .el-group-title.ccui-group-wrapper .extend-btn {
  top: 2px;
}
/deep/ .file-group .el-group-title .group-content {
  margin-top: 40px;
}
</style>
